<template>
  <div v-if="is_login">

    <div class="login-container">
      <div class="banner_img" style="display: flex;justify-content: center" />

      <el-form ref="form" :model="form" :rules="Rules" label-width="200px" label-position="top">
        <template v-for="item in formJosn2">
          <template v-if="item.type == 'input'">
            <el-form-item :key="item.key" :label="item.label">
              <el-input v-model="form[item.key]" :placeholder="item.placeholder" />
            </el-form-item>
          </template>

          <template v-if="item.type == 'text'">
            <el-form-item :key="item.key" label="">
              <p style="font-size:12px;margin-top: 0px;line-height: 14px;">{{ item.label }}</p>
            </el-form-item>
          </template>
          <template v-if="item.type == 'title'">
            <el-form-item :key="item.key" label="">
              <p style="font-size:22px;margin-bottom: 0px; text-align: center;">{{ item.label }}</p>
            </el-form-item>
          </template>
        </template>

        <el-form-item class="idcard_img">
          <el-upload
            class="avatar-uploader"
            :data="dataObj"
            action="http://up-z2.qiniup.com"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"
          >
            <div v-if="form.filePath">
              <el-image style="width: 100%; " :src="form.filePath" fit="contain" class="avatar" />
              点击图片重新上传
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon">身份证正面</i>
          </el-upload>
        </el-form-item>

        <el-form-item class="idcard_img">
          <el-upload
            class="pic-uploader"
            :data="dataObj"
            action="http://up-z2.qiniup.com"
            :show-file-list="false"
            :on-success="handleSuccessPic"
            :on-error="uploadError"
            :before-upload="beforeUploadPic"
          >
            <div v-if="form.pic">
              <el-image style="width: 100%; " :src="form.pic" fit="contain" class="">点击图片重新上传</el-image>
              点击图片重新上传
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon">人像正面</i>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <div class="submit" style="display:flex">
            <el-button type="primary" @click="showQrcode()">展示二维码</el-button>
          </div>
          <div class="submit" style="display:flex">
            <el-button type="danger" @click="logout()">清除登录</el-button>
          </div>
        </el-form-item>
        <el-form-item />
      </el-form>
    </div>

    <el-dialog title="二维码展示" :visible.sync="dialogVisible" width="95%">

      <div class="showQrecode">
        <!-- <div class="id_box">{{ (form.id) }}</div> -->
        <div class="canvas_box"><canvas id="QrCode" ref="QrCode" /></div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">確 定</el-button>
      </span>
    </el-dialog>

  </div>

  <!-- 未登录之前 -->
  <div v-else>
    <div class="login-container">
      <div class="banner_img" style="display: flex;justify-content: center">
        <el-image
          style="height: 100px;margin-top: 15%;"
          src="https://img.wenfree.cn/logo/logo-yunkong.png"
          fit="contain"
        />
      </div>

      <el-form ref="form" :model="form" :rules="Rules" label-width="200px" label-position="top">

        <template v-for="item in formJosn">
          <template v-if="item.type == 'input'">
            <el-form-item :key="item.key" :label="item.label">
              <el-input v-model="form[item.key]" :placeholder="item.placeholder" />
            </el-form-item>
          </template>

          <template v-if="item.type == 'text'">
            <el-form-item :key="item.key" label="">
              <p style="font-size:16px;margin-top: 0px;margin-bottom: 0px;text-align: center;">{{ item.label }}</p>
            </el-form-item>
          </template>
          <template v-if="item.type == 'title'">
            <el-form-item :key="item.key" label="">
              <p style="font-size:22px;margin-bottom: 0px;margin-top: 0px; text-align: center;">{{ item.label }}</p>
            </el-form-item>
          </template>
        </template>

        <el-form-item label="请输入验证码" class="code">
          <el-input v-model="code" class="code_input" placeholder="验证码" />
          <el-image style="margin-left: 20px;" :src="code_img" fit="contain" @click="getCodeImgByYesApi" />
        </el-form-item>

        <el-form-item>
          <div class="submit" style="display:flex">
            <el-button type="primary" :disabled="is_submit_ing" @click="submit()">{{ submit_state }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>

import { checkInfo, getCodeImg, face } from '@/api/jdApi'
import { getToken } from '@/api/qiniu'
import QRCode from 'qrcode'

export default {

  name: 'Registration',
  components: {

  },
  data() {
    return {
      dialogVisible: false,
      id: '',
      code_Verify: '',
      code_info: [],
      code_img: '',
      code: '',
      is_login: false,
      formJosn: [
        { label: '非常检单，就是好用', type: 'text', placeholder: '', key: 'disc' },
        { label: '核验码', type: 'title', placeholder: '', key: 'dis' },
        { label: '姓名', type: 'input', placeholder: '请输入姓名', key: 'Name' },
        { label: '手机号', type: 'input', placeholder: '请输入手机号', key: 'phone' },
        { label: '身份证号', type: 'input', placeholder: '请输入身份证号', key: 'IdNum' }
      ],
      formJosn2: [
        { label: '核验码', type: 'title', placeholder: '', key: 'dis' },
        { label: '姓名', type: 'input', placeholder: '请输入姓名', key: 'Name' },
        { label: '手机号', type: 'input', placeholder: '请输入手机号', key: 'phone' },
        { label: '身份证号', type: 'input', placeholder: '请输入身份证号', key: 'IdNum' },
        { label: '相似度', type: 'input', placeholder: '相似度', key: 'likes' }
      ],
      form: {
        Name: '',
        phone: '',
        IdNum: '',
        Address: '',
        filePath: '',
        pic: '',
        likes: ''
      },
      Rules: {
        Name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在2到4个字符', trigger: 'blur' }
        ]
      },
      options: {
        penColor: 'black', // 筆刷顔色
        minWidth: 2 // 最小寬度
      },
      qmValue: '',
      save_key: false,
      agree: false,
      dialogVisible: false,
      dataObj: { token: '', key: '', data: {}, bucket: 'hongkongidcard' },
      image_uri: [],
      fileList: [],
      suffix: '',
      is_submit_ing: false,
      submit_state: '完善信息'
    }
  },
  watch: {
    'form.filePath'() {
      console.log('filePath', this.form.filePath)
    },
    deep: true
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    // this.getCodeImgByYesApi()
    this.is_login_init()
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    is_login_init() {
      this.is_login = localStorage.getItem('is_login') ? localStorage.getItem('is_login') : false
      if (!this.is_login) {
        this.getCodeImgByYesApi()
      }
      this.form = localStorage.getItem('form') ? JSON.parse(localStorage.getItem('form')) : this.form
      console.log('form-inti', this.form)
      if (localStorage.getItem('likes')) {
        this.form.likes = localStorage.getItem('likes')
      }
    },
    logout() {
      localStorage.removeItem('is_login')
      this.is_login_init()
      this.is_submit_ing = false
      this.submit_state = '完善资料'
    },
    submit() {
      console.log('准备登录')

      const that = this

      console.log('准备展示', this.code, 'code_Verify', this.code_Verify, this.form)
      if (this.code != this.code_Verify) {
        this.$alert('验证码错误', '提示', {
          confirmButtonText: '确定'
        })
        return
      }

      if (this.form.pic && this.form.filePath) {
        const facedata = { UrlA: this.form.filePath, UrlB: this.form.pic }
        this.check_face(facedata)
      }

      checkInfo(this.form).then(response => {
        console.log('返回的form', response.data)
        this.id = response.data.id
        that.form = response.data
        this.is_login = true
        localStorage.setItem('is_login', this.is_login)

        localStorage.setItem('likes', response.data.likes)

        console.log('准备存入form', JSON.stringify(response.data))
        localStorage.setItem('form', JSON.stringify(response.data))

        console.log('本地form', that.form)
        console.log('读出的form', JSON.parse(localStorage.getItem('form')))

        that.form.likes = response.data.likes
      }).catch(err => {
        console.log(err)
      })

      this.is_submit_ing = true
      this.submit_state = '正在核验'
    },
    beforeUpload(file) {
      console.log(file.name, file)
      console.log(this.fileList)

      const _self = this
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          const key = response.data.key
          const token = response.data.token
          _self._data.dataObj.token = token
          _self._data.dataObj.key = key

          _self._data.dataObj.key = `jdIdcard/filePath/anqi_${_self.form.IdNum}_.jpg`

          console.log('_self', _self.dataObj)
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    },
    beforeUploadPic(file) {
      console.log(file.name, file)
      console.log(this.fileList)

      const _self = this
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          const key = response.data.key
          const token = response.data.token
          _self._data.dataObj.token = token
          _self._data.dataObj.key = key

          _self._data.dataObj.key = `jdIdcard/Pic/anqi_${_self.form.IdNum}_.jpg`

          console.log('_self', _self.dataObj)
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    },
    handleSuccess(val) {
      const self = this
      console.log('成功', val)
      const filePath = 'https://hongkongidcard.wenfree.cn/' + val.key
      self.form.filePath = filePath
      console.log('this.form.filePath', self.form.filePath)
      // Just to simulate the time of the request
      setTimeout(() => {
        console.log('更新')
        this.submit()
        this.$forceUpdate()
        self.form.filePath = filePath
      }, 0.2 * 1000)
    },
    handleSuccessPic(val) {
      const self = this
      console.log('成功', val)
      const pic = 'https://hongkongidcard.wenfree.cn/' + val.key
      self.form.pic = pic
      console.log('this.form.filePath', self.form.pic)
      // Just to simulate the time of the request
      setTimeout(() => {
        console.log('更新')
        this.submit()
        this.$forceUpdate()
        self.form.pic = pic
      }, 0.2 * 1000)
    },
    uploadError(val) {
      console.log('uploadError', val)
    },
    handleRemove(val) {
      console.log('handleRemove', val)
    },
    getCodeImgByYesApi() {
      const sefl = this
      console.log('准备生成验证码')
      getCodeImg({}).then(response => {
        console.log('验证码', response)
        sefl.code_info = response
        sefl.code_img = response.data.img_url
        sefl.code_Verify = response.data.code
      })
    },
    showQrcode() {
      this.dialogVisible = true
      this.$nextTick(() => {
        console.log('显示二维码的元素(div)=' + this.$refs.QrCode)
        // 生成的二维码内容，可以添加变量
        const txt = this.form.id.toString()
        const canvas = document.getElementById('QrCode')
        QRCode.toCanvas(canvas, txt, { width: 200, height: 200 }, error => {
          if (error) console.error('e', error)
          console.log('二维码 生成成功!')
        })
      })
    },
    useqrcode() {
      this.$nextTick(function() {
        // 生成的二维码内容，可以添加变量
        const txt = this.form.id
        const canvas = document.getElementById('QrCode')
        QRCode.toCanvas(canvas, txt, error => {
          if (error) console.error('e', error)
          console.log('二维码 生成成功!')
        })
      })
    },
    check_face(data) {
      const that = this
      console.log('facedata', data)
      face(data).then(response => {
        console.log('人脸比对', response.Score)
        that.form.likes = response.Score
        this.$forceUpdate()
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss">
/* 修複input 背景不協調 和光標變色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
.login-container {
  padding: 10px;
}

.el-form-item__label {
  padding: 0 !important;
}

.el-form-item {
  margin-bottom: 5px;
}

.submit {
  display: flex;
  margin-top: 15px;
  margin-bottom: 15px;

  button {
    width: 100%;
  }
}

.code_input {
  width: 56%;
}

.code .el-form-item__content {
  display: flex;
}

.code img {
  border-radius: 4px;
}

.el-upload-dragger {
  opacity: 1;
  // background: #373737d6;
  width: 100% !important;
}

.idcard_img .el-upload {
  width: 100%;
}

.el-upload-dragger .el-upload__text {
  color: #fff;
}

.idcard_img .el-upload {
  // background: url('https://hongkongidcard.wenfree.cn/idcard.png') no-repeat !important;
  background-size: 100% 100% !important;
  // filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='https://hongkongidcard.wenfree.cn/idcard.png', sizingMethod='scale');
  opacity: 0.8;
  // border: 1px #000 solid;
  // border-radius: 10px;
}

.pic-uploader .el-upload,
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.showQrecode {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

@media screen and (max-width: 500px) {
  .el-message {
    min-width: 300px !important;
  }
}

@media screen and (max-width: 500px) {
  .el-message-box {
    width: 300px !important;
  }
}

@media screen and (max-width: 500px) {
  .el-dialog__wrapper .el-dialog {
    width: 90% !important;

    .el-dialog__body {
      padding: 10px 20px !important;

      .el-form-item__label {
        width: 68px !important;
      }

      .el-select,
      .el-input {
        width: 180px !important;
      }
    }
  }
}
</style>
